package com.remoter.context.spring.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import com.remoter.basic.bean.support.ProviderModule;
import com.remoter.basic.configure.IConfiguration;
import com.remoter.basic.configure.support.AbstractConfiguration;
import com.remoter.basic.context.IContext;
import com.remoter.basic.util.Final;
import com.remoter.basic.util.ServiceLoader;

/**
 * @author			koko
 * @date 			2017-08-09 16:25:30
 * @description 	类功能说明
 */
public class ProviderBean extends ProviderModule implements InitializingBean, DisposableBean, BeanNameAware{
	
	private static final long serialVersionUID = -8631412197565045572L;
	private static final Logger logger = LoggerFactory.getLogger(ProviderBean.class);
	
	private static IContext context;
	
	private transient String name;
	private String id;
	private ProviderModule module;
	
	@Override
	public void setBeanName(String name) {
		this.name = name;
	}

	@Override
	public void destroy() throws Exception {
		context.detachProviderModule(this.module);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		
	}

	public void init(){
		try{
			IConfiguration configuration = AbstractConfiguration.getConfiguration();
			context = ServiceLoader.getService(IContext.class,configuration.getOption(Final.O_VAL_CONTEXT));
			this.module = context.createProviderModule(this.getProtocol());
			this.module.setType(this.getType());
			this.module.setBean(this.name);
			this.module.setInstance(this.getInstance());
			context.attachProvider(this.module);
		}catch(Exception e){
			logger.error(e.getMessage(),e);
		}
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
}